package com.interview.javabase.algorithm;

/**
 * @author: zsg
 * @description:
 * @date: 2019/9/1 11:31
 * @modified:
 */
public class MergeSort {

    /**
     * 合并两个有序的子序列
     *
     * @param arr   需要进行排序的数组
     * @param left  最左的值的下标
     * @param mid   中间的值下标
     * @param right 最右的值下标
     * @param temp  需要赋值的临时数组
     */
    public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        int i = left;
        int j = mid + 1;
        // temp 数组的下标
        int k = 0;

        while (i <= mid && j <= right) {
            if (arr[i] <= arr[j]) {
                temp[k++] = arr[i++];
            } else {
                temp[k++] = arr[j++];
            }
        }

        while (i <= mid) {
            temp[k++] = arr[i++];
        }

        while (j <= right) {
            temp[k++] = arr[j++];
        }

        // 把temp 赋值给arr
        int t = 0;
        int leftTemp = left;
        while (leftTemp <= right) {
            arr[leftTemp++] = temp[t++];
        }
    }

    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left >= right) {
            return;
        }

        int mid = (left + right) / 2;

        // 向左边拆分
        mergeSort(arr, left, mid, temp);

        // 向右拆分
        mergeSort(arr, mid + 1, right, temp);

        // 合并
        merge(arr, left, mid, right, temp);
    }

    public static void main(String[] args) {

        int[] arr = {9, 3, 12, 1, 253, 634, 2, 12, 313, 531, 64, 52, 3, 23, 523, 15, 13};

        int[] temp = new int[arr.length];
        mergeSort(arr, 0, arr.length - 1, temp);
        for (Integer integer : arr) {
            System.out.print(integer + " ");
        }
    }
}
